import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
//引入定义的ts类型
import type { UserInfoState } from "./interface";
import router from "@/router/index";
import cloneDeep from 'lodash/cloneDeep';
import type {
  LoginRequestResult,
  getRequestUserInfo,
} from "@/api/user/type/index";
// import { ElMessage } from "element-plus";
//引入静态路由所有对象
import { staticRoutes, asyncRoutes, anyRoutes } from "@/router/routes";
import { loginUser, getUserInfo, loginOut } from "@/api/user/user";

// 筛选路由函数
const findOKrutes = (ownIncode: any, reqRute: any) => {
  return ownIncode.filter((item: any) => {
    if (reqRute.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = findOKrutes(item.children, reqRute);
      }
      return true;
    }
  });
};

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    //用户名
    name: "",
    //头像
    avatar: "",
    menuRoutes: [],
    //按钮权限列表
    buttonIsCanList: [],
  }),

  actions: {
    //登陆函数
    async loginUser(username: string, password: string) {
      const result: LoginRequestResult = await loginUser({
        username,
        password,
      });

      this.token = result.token;
      setToken(result.token);
    },
    //获取用户信息函数
    async getInfo() {
      const result: getRequestUserInfo = await getUserInfo();
      this.name = result.name;
      this.avatar = result.avatar;
      //存储路由对象
      // this.menuRoutes = staticRoutes;
      // console.log(result);
      const asyncroute = findOKrutes(cloneDeep(asyncRoutes), result.routes);
      this.menuRoutes = [...staticRoutes, ...asyncroute, ...anyRoutes];
      //路由实例赋值合并
      [...asyncroute, ...anyRoutes].forEach((item) => {
        router.addRoute(item);
        console.log(router);
      });
      this.buttonIsCanList = result.buttons;
    },
    //退出登陆
    async reset() {
      await loginOut();
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.name = "";
      this.avatar = "";
      //删除所有路由信息
      router.getRoutes().forEach((item: any) => {
        router.removeRoute(item.name);
      });
      //重新添加静态路由
      staticRoutes.forEach((item: any) => {
        router.addRoute(item);
      });
    },
  },
});
